import pubsub from './pubsub';
import hybrid from '@haohuawu/whaleyvr-hybrid-sdk-js';

const state = pubsub();

let deprecated = false;

function isDeprecated() {
  return deprecated;
}

const share = (function() {
  if (window.webkit && window.webkit.messageHandlers) {
    if (window.webkit.messageHandlers.jsShare) {
      deprecated = true;
      return function(message) {
        window.webkit.messageHandlers.jsShare.postMessage(JSON.stringify(message));
      };
    }
    if (window.webkit.messageHandlers.jsShare2) {
      return function(message) {
        window.webkit.messageHandlers.jsShare2.postMessage(JSON.stringify(message));
      };
    }
  }
  if (window.jsShare) {
    deprecated = true;
    return function(message) {
      window.jsShare.postMessage(JSON.stringify(message));
    };
  }
  if (window.jsShare2) {
    return function(message) {
      window.jsShare2.postMessage(JSON.stringify(message));
    };
  }
  return function(message) {
    hybrid.share(message).then(result => {
      window.jsShareResult(result);
    });
  };
})();

const on = state.subscribe;
const off = state.unsubscribe;

window.jsShareResult = function({ status, platform }) {
  state.publish((status === true || status === 1)? 'success': 'failure', { platform });
};

export default {
  share,
  on,
  off,
  isDeprecated
};
